<template>
  <div>
    <!-- 文件上传组件 -->
    <el-upload
        action="http://localhost:8081/sys/file/upload"
        list-type="picture-card"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-error="handleError"
        :file-list="fileList"
        :limit="3"
        :on-exceed="handleExceed"
        :headers="headers"
        :data="uploadData"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>

<script>
import { ref } from 'vue';
import { getToken } from "@/utils/auth";
import { ElMessage } from 'element-plus';
export default {
  setup() {
    const fileList = ref([]);

    // 自定义请求头，根据需求添加，比如携带 token 等
    const headers = ref({
      'Authorization': 'Bearer '+getToken(), // 如果需要认证，可以在这里加入 token
    });

    // 如果后端需要额外的参数，可以通过 data 传递
    const uploadData = ref({
      extraField: 'extraData', // 根据后端需求自定义
    });

    // 文件移除时的回调
    const handleRemove = (file, fileList) => {
      console.log('Removed file:', file);
      console.log('Remaining files:', fileList);
    };

    // 文件上传成功时的回调
    const handleSuccess = (response, file, fileList) => {
      console.log('File uploaded successfully:', response);
      // this.$message.success('文件上传成功');
	  ElMessage.success('文件上传成功')
    };

    // 文件上传失败时的回调
    const handleError = (err, file, fileList) => {
      console.error('File upload failed:', err);
      // this.$message.error(`文件上传失败: ${err.message}`);
	  ElMessage.error("文件上传失败")
    };

    // 文件超出限制时的回调
    const handleExceed = (files, fileList) => {
		ElMessage.info(`最多上传 3 个文件，你选择了 ${files.length} 个文件，当前总共选择了 ${files.length + fileList.length} 个文件`)
      // this.$message.warning(`最多上传 3 个文件，你选择了 ${files.length} 个文件，当前总共选择了 ${files.length + fileList.length} 个文件`);
    };

    return {
      fileList,
      headers,
      uploadData,
      handleRemove,
      handleSuccess,
      handleError,
      handleExceed,
    };
  },
};
</script>

<style scoped>
.el-upload {
  width: 160px;
  height: 160px;
  text-align: center;
  line-height: 160px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.el-upload:hover {
  border-color: #409eff;
}

.el-upload i {
  font-size: 48px;
  color: #d9d9d9;
}

.el-upload i:hover {
  color: #409eff;
}
</style>
